using System;
using System.Text;
using System.Data;
using System.Collections;
using System.Collections.Generic;

using Framework;

namespace SchemaMonitor
{
    //Table-Mapping Class (Customisable half)
    public partial class CChapter
    {
        #region Constants
        #endregion

        #region Constructors (Public)
        //Default Connection String
        public CChapter() : base() {}

        //Alternative Connection String
        public CChapter(CDataSrc dataSrc) : base(dataSrc) {}
        
        //Hidden  (UI code should use cache instead)
        protected internal CChapter(int chapterSectionId) : base(chapterSectionId) {}
        protected internal CChapter(CDataSrc dataSrc, int chapterSectionId) : base(dataSrc, chapterSectionId) {}
        protected internal CChapter(CDataSrc dataSrc, int chapterSectionId, IDbTransaction txOrNull) : base(dataSrc, chapterSectionId, txOrNull) { }
        #endregion

        #region Default Values
        protected override void InitValues_Custom()
        {
            //_sampleDateCreated = DateTime.Now;
            //_sampleSortOrder   = 0;
        }
        #endregion
        
        #region Default Connection String
        protected override CDataSrc DefaultDataSrc()  { return CDataSrc.Default;  }
		#endregion

		#region Properties - Relationships
		//Relationships - Foriegn Keys (e.g parent)


		public CSection Section { get { return CSection.Cache.GetById(this.ChapterSectionId); } }
		private CNode _node;
		public CNode Node_(CUser u)
		{
			if (null == _node)
				_node = u.All.GetById(this.ChapterNodeGuid);
			return _node;
		}
		[Obsolete]
		public CNode Node
		{
			get
			{
				if (null == _node && Guid.Empty != _chapterNodeGuid)
					_node = new CNode(this.ChapterNodeGuid);
				return _node;
			}
			set
			{
				_node = value;
				if (null == value)
					_chapterNodeGuid = Guid.Empty;
				else
					_chapterNodeGuid = _node.NodeGuid;
			}
		}


		//Relationships - Collections (e.g. children)
		public    CChapterPictureList ChapterPictures                     {  get { return CChapterPicture.Cache.GetByChapterId(          this.ChapterId); }  }
        protected CChapterPictureList ChapterPictures_(IDbTransaction tx) {        return new CChapterPicture(DataSrc).SelectByChapterId(this.ChapterId, tx); } //Only used for cascade deletes

		public CNodeLabelList NodeLabels { get { return CNodeLabel.Cache.GetByNodeGuid(this.ChapterNodeGuid); } }
		protected CNodeLabelList NodeLabels_(IDbTransaction tx) { return new CNodeLabel(DataSrc).SelectByNodeGuid(this.ChapterNodeGuid, tx); } //Only used for cascade deletes

		public CNodeLabels_OneToOneList NodeLabels_OneToOnes { get { return CNodeLabels_OneToOne.Cache.GetByNodeGuid(this.ChapterNodeGuid); } }
		protected CNodeLabels_OneToOneList NodeLabels_OneToOnes_(IDbTransaction tx) { return new CNodeLabels_OneToOne(DataSrc).SelectByNodeGuid(this.ChapterNodeGuid, tx); } //Only used for cascade deletes

		//Relationships - 2-Step Walk

		public CNodeLabels_OneToOne Rating_ { get { return NodeLabels_OneToOnes.GetByType_(CTagType.Cache.FB_PostRating.TypeId); } }
		public CMetaTag Rating { get { return NodeLabels_OneToOnes.GetByType(CTagType.Cache.FB_PostRating.TypeId); } }
		public int RatingTagId
		{
			get
			{
				return null == Rating ? 0 : Rating.TagId;
			}
			set
			{
				if (value <= 0)
				{
					if (null != Rating)
						Rating.Delete();
				}
				else
				{
					if (null == Rating)
					{
						var m = new CNodeLabels_OneToOne()
						{
							LabelNodeGuid = this.ChapterNodeGuid,
							LabelTypeId = CTagType.Cache.FB_PostRating.TypeId,
							LabelTagId = value
						};
						m.Save();
					}
					else
					{
						Rating_.LabelTagId = value;
						Rating_.Save();	
					}
				}
			}
		}

		public CMetaTagList MetaTags { get { return NodeLabels.Metatags; } }
		public CMetaTagList RemainingMetaTags(string search) { return NodeLabels.RemainingMetatags(search); }

		public CMetaTagList MetaTags_O2O { get { return NodeLabels_OneToOnes.Metatags; } }
		public CMetaTagList RemainingMetaTags_O2O(string search) { return NodeLabels_OneToOnes.RemainingMetatags(search); }
		#endregion

		#region Properties - Customisation
		//Derived/ReadOnly (e.g. xml classes, presentation logic)
		public string FullName
		{
			get
			{
				return string.Concat(Section.FullName, " :: ", NameAndCount);
			}
		}
		public string NameAndCount { get { return Framework.CUtilities.NameAndCount(CUtilities.Truncate( ChapterName), ChapterPictures); } }
		#endregion

		#region Save/Delete Overrides
		public override void Delete(IDbTransaction txOrNull)
		{
			//Use a transaction if none supplied 
			if (txOrNull == null)
			{
				BulkDelete(this);
				return;
			}

			//Normal Delete 
			base.Delete(txOrNull);
		}
		#endregion

		#region Custom Database Queries
		//(Not normally required for cached classes, use list class for searching etc)
		//For Stored Procs can use: MakeList (matching schema), or DataSrc.ExecuteDataset (reports etc)
		//For Dynamic sql, can use: SelectSum, SelectDistinct, SelectCount, SelectWhere (inherited methods)
		#endregion

		#region Searching (Optional)
		//For cached classes, custom seach logic resides in static methods on the list class
		// e.g. CChapter.Cache.Search("...")

		//See also the auto-generated methods based on indexes
		//' e.g. CChapter.Cache.GetBy...
		#endregion

		#region Caching Details
		//Cache Key
		internal static string CACHE_KEY = typeof(CChapter).ToString();    //TABLE_NAME

        //Cache data
        private static CChapterList LoadCache()  {   return new CChapter().SelectAll();   }
        //Cache Timeout
        private static void SetCache(CChapterList value)
        {
            if (null != value)  
                value.Sort(); 
            CCache.Set(CACHE_KEY, value);    //Optional parameter can override timeout (otherwise uses config-settings, which default to 3hrs)
        }
        //Helper Method
        private CChapter CacheGetById(CChapterList list)  { return list.GetById(this.ChapterSectionId);    }
        #endregion

        #region Cloning
        public CChapter Clone(CDataSrc target, IDbTransaction txOrNull) //, int parentId)
        {
            //Shallow copy: Copies the immediate record, excluding autogenerated Pks
            CChapter copy = new CChapter(this, target);

            //Deep Copy - Child Entities: Cloned children must reference their cloned parent
            //copy.SampleParentId = parentId;

            copy.Save(txOrNull);

            //Deep Copy - Parent Entities: Cloned parents also clone their child collections
            //this.Children.Clone(target, txOrNull, copy.ChapterSectionId);

            return copy;
        }
        #endregion

        #region ToXml
        protected override void ToXml_Custom(System.Xml.XmlWriter w)
        {
            //Store(w, "Example", this.Example)
        }
        #endregion
    }
}